<template>
    <div>
        <Spin fix v-if="ifSpin">
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
            <div>附件生成中</div>
        </Spin>
        <Form :label-width="80" ref="formInline" :model="formInline">
            <Row :gutter="16" class="query-form2">
                <i-col span="8">
                    <FormItem label="时间：" prop="se_date">
                        <DatePicker v-model="formInline.se_date" type="datetimerange" style="width: 100%" format="yyyy-MM-dd" placeholder="请选择查询时间（开始，结束）"></DatePicker>
                    </FormItem>
                </i-col>
                <i-col span="8">
                    <FormItem label="专业：" prop="userName">
                        <Select v-model="formInline.type" filterable>
                            <Option v-for="(item, index) in typeList" :value="item.id" :key="index">{{item.name}}</Option>
                        </Select>
                    </FormItem>
                </i-col>
                <i-col span="8">
                    <div style="float: right;">
                        <Button class="ivu-btn-query"  icon="md-search"  @click="query">查询</Button>
                        <Button class="ivu-btn-reset" style="margin-left: 10px" @click="cancel">重置</Button>
                    </div>
                </i-col>
            </Row>
        </Form>
        <Row type="flex" justify="start" class="query-form">
            <i-col>
                <Button icon="md-cloud-download" class="ivu-btn-add" @click="exportExcel">导出</Button>
            </i-col>
        </Row>
        <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns" no-data-text="没有查询到相关数据！"
               :data="infos" width="100%"  :height="tableHeight" highlight-row stripe size="small"></Table>
        <Row type="flex" justify="end" >
          <i-col>
            <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                  @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
          </i-col>
        </Row>
    </div>
</template>

<script>

    import {sessionStorage} from '@/common/cacheUtils.js';
    import {Api} from '../../../api'

    export default {
        name: "apsgItemCount",
        data(){
            return{
                ifSpin: false,
                loading: false,
                formInline: {
                    se_date: []
                },
                tableHeight: '',
                columns: [
                    {
                        type: 'index',
                        title: '序号',
                        width: 80,
                        align: 'center',
                        fixed: 'left',
                    },
                    {
                        title: '条目编码',
                        align: 'center',
                        key: 'name',
                    },
                    {
                        title: '条目内容',
                        align: 'center',
                        key: 'content',
                    },
                    {
                        title: '发生频次',
                        align: 'center',
                        key: 'frequency',
                    },
                ],
                infos: [],
                typeList: [],
                pagedata: {
                  total: 0,
                  pageSize: 10,
                  currentPage: 1
                },
                pageSizeArray: [10, 20, 50],
            }
        },
        mounted() {
            this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
            this.formInline.se_date = [this.getCurrentMonthFirst(), this.getCurrentMonthLast()];
            this.getItemType();
            this.query();
        },
        methods: {
            query(){
                let user = sessionStorage('userId').getObject('userId');
                let data = {
                    orgId: user.companyId,
                    startPage: this.pagedata.currentPage,
                    pageSize: this.pagedata.pageSize,
                };
                if(this.formInline.se_date[0]!='' && this.formInline.se_date[1]!=''){
                    data.startDate = this.formatDate(new Date(this.formInline.se_date[0]), 'yyyy-MM-dd');
                    data.endDate = this.formatDate(new Date(this.formInline.se_date[1]), 'yyyy-MM-dd');
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.loading = true;
                this.$http.get(Api.apsgItemCount, {
                    params: data
                }).then(function(res){
                    this.infos = res.data.data;
                    this.pagedata.total = res.data.totalSize;
                    this.loading = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            cancel(){
                this.formInline = {
                    se_date: [this.getCurrentMonthFirst(), this.getCurrentMonthLast()]
                };
                this.query();
            },
            getItemType(){
                this.$http.get(Api.apsgItemTypeLevel ).then(function(res){
                    if(res.data.status == 200){
                        this.typeList = res.data.data;
                    }else{
                        this.$Message.error({
                            content: '查询失败',
                            duration: 4
                        });
                    }
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            exportExcel(){
                let user = sessionStorage('userId').getObject('userId');
                let data = {
                    orgId: user.companyId
                };
                if(this.formInline.se_date[0]!='' && this.formInline.se_date[1]!=''){
                    data.startDate = this.formatDate(new Date(this.formInline.se_date[0]), 'yyyy-MM-dd');
                    data.endDate = this.formatDate(new Date(this.formInline.se_date[1]), 'yyyy-MM-dd');
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.ifSpin = true;
                this.$http.get(Api.apsgItemCount + '/excel',{
                    params: data,
                    responseType: 'arraybuffer'
                }).then((res) => {
                    this.ifSpin = false;
                    const aLink = document.createElement("a");
                    let blob = new Blob([res.data], {
                        type: "application/vnd.ms-excel"
                    })
                    aLink.href = URL.createObjectURL(blob);
                    aLink.download = "隐患条目发生频次统计表.xlsx" //标题
                    aLink.click();
                    document.body.appendChild(aLink);
                })
            },
            formatDate(date, fmt) {
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
                }
                let o = {
                    'M+': date.getMonth() + 1,
                    'd+': date.getDate(),
                    'h+': date.getHours(),
                    'm+': date.getMinutes(),
                    's+': date.getSeconds()
                };
                for (let k in o) {
                    if (new RegExp(`(${k})`).test(fmt)) {
                        let str = o[k] + '';
                        fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
                    }
                }
                return fmt;
            },
            padLeftZero(str) {
                return ('00' + str).substr(str.length);
            },
            getCurrentMonthFirst(){
                let date = new Date();
                date.setDate(1);
                let month = parseInt(date.getMonth()+1);
                let day = date.getDate();
                if (month < 10) {
                    month = '0' + month
                }
                if (day < 10) {
                    day = '0' + day
                }
                return date.getFullYear() + '-' + month + '-' + day;
            },
            getCurrentMonthLast(){
                let date=new Date();
                let currentMonth=date.getMonth();
                let nextMonth=++currentMonth;
                let nextMonthFirstDay=new Date(date.getFullYear(),nextMonth,1);
                let oneDay=1000*60*60*24;
                let lastTime = new Date(nextMonthFirstDay-oneDay);
                let month = parseInt(lastTime.getMonth()+1);
                let day = lastTime.getDate();
                if (month < 10) {
                    month = '0' + month
                }
                if (day < 10) {
                    day = '0' + day
                }
                return date.getFullYear() + '-' + month + '-' + day;
            },
            pageSizeChange(pageSize){
              this.pagedata.pageSize = pageSize;
              this.query();
            },
            pageChange(pageNum){
              this.pagedata.currentPage = pageNum;
              this.query();
            },
        }
    }
</script>

<style scoped>
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
</style>
